package com.sdtv.basemodule.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Layout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;

import com.blankj.utilcode.util.LogUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.sdtv.basemodule.config.AppConfig;
import com.sdtv.basemodule.config.life.AppManager;
import com.sdtv.basemodule.http.cookie.PersistentCookieStore;
import com.sdtv.basemodule.mvp.IView;
import com.sdtv.basemodule.mvp.presenter.PresenterDispatch;
import com.sdtv.basemodule.mvp.presenter.PresenterProviders;
import com.sdtv.basemodule.router.ARouterUtils;
import com.sdtv.basemodule.widget.ContentViewWithToolBar;
import com.sdtv.basemodule.widget.gloading.Gloading;
import com.trello.lifecycle2.android.lifecycle.AndroidLifecycle;
import com.trello.rxlifecycle3.LifecycleProvider;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @ProjectName: MediunFusion
 * @Package: com.sdtv.basemodule.base
 * @ClassName: BaseActivity
 * @Description: java类作用描述
 * @Author: 小郭同学
 * @CreateDate: 2019-06-19 14:06
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public abstract class BaseActivity extends AppCompatActivity implements IView {

    //butterknife绑定
    private Unbinder unbinder;

    public Activity context;
    //显示状态view
    public Gloading.Holder holder;
    //presenter注解相关
    protected PresenterProviders mPresenterProviders;
    protected PresenterDispatch mPresenterDispatch;

    /**
     * 软键盘管理
     */
    private InputMethodManager mInputMethodManager;
    //显示dialog --- 单点登录 被登出的提示
    private AlertDialog kickOutDialog;
    //带有toolbar的view
    private ContentViewWithToolBar contentViewWithToolBarView;
    //布局控件  不带有toolbar
    private View contentView;
    // toolbar
    protected View toolbarView;

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        return super.onCreateView(name, context, attrs);
    }

    @Override
    public void finish() {
        super.finish();
        hideSoftKeyBoard();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onBeforeSetContentLayout();
        this.context = this;
        if (0 != getLayoutId() && showToolBar()) {
            // 显示toolbar的情况下 需要拼装上toolBar
            contentViewWithToolBarView = new ContentViewWithToolBar(this, getLayoutId());
            setContentView(contentViewWithToolBarView);
            contentView = contentViewWithToolBarView.getContentView();
            toolbarView = contentViewWithToolBarView.getToolBar();
            // 初始化toolbar
            initToolBar();
        } else {
            // 不显示toolbar 直接把layout的内容填充到页面
            contentView = LayoutInflater.from(this).inflate(getLayoutId(), null);
            setContentView(contentView);
        }
        unbinder = ButterKnife.bind(this);
        //初始化presenter
        mPresenterProviders = PresenterProviders.inject(this);
        mPresenterDispatch = new PresenterDispatch(mPresenterProviders);
        //绑定view
        mPresenterDispatch.attachView(this, this);
        mPresenterDispatch.onCreatePresenter(savedInstanceState);
        //Arouter注入
        ARouterUtils.injectActivity(this);
        initStatusBar();
        initView();
        initData();
    }

    /**
     * 设置内容区域之前需要做的操作-
     */
    protected void onBeforeSetContentLayout() {

    }

    /**
     * 初始化toolbar
     */
    protected void initToolBar() {

    }

    /**
     * 是否显示toolbar
     * 默认显示toolbar
     */
    protected boolean showToolBar() {
        return true;
    }

    /**
     * 初始化状态栏
     */
    protected void initStatusBar() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(AppConfig.INSTANCE.getConfig().getStatusColor())
                // 设置状态栏字体颜色
//                .statusBarDarkFont(true, 0.2f)
                //解决软键盘与底部输入框冲突问题
                .keyboardEnable(true)
                .init();
    }


    /**
     * 设置布局文件ID
     *
     * @param
     * @return
     */
    public int getLayoutId() {
        return 0;
    }


    /**
     * 初始化页面布局
     */
    public abstract void initView();

    /**
     * 初始化页面数据
     */
    public abstract void initData();


    @Override
    protected void onDestroy() {
        if (null != unbinder && unbinder != Unbinder.EMPTY) {
            unbinder.unbind();
        }
        this.context = null;
        mPresenterDispatch.onDestroyPresenter();
        //关闭键盘
        hideSoftKeyBoard();
        super.onDestroy();
        if (kickOutDialog != null && kickOutDialog.isShowing()) {
            kickOutDialog.cancel();
        }
    }

    /**
     * 初始化holder
     */
    @Override
    public void initGloadingView() {
        if (null == holder) {
            holder = Gloading.getDefault().wrap(contentView).
                    withRetry(() -> {
                        onLoadRetry();
                    });
        }
    }


    /**
     * 显示错误页面
     * --有两种 1、加载数据失败  2. 网络异常错误
     */
    @Override
    public void onError() {
        if (null == holder) {
            initGloadingView();
        }
        if (holder != null) {
            holder.showLoadFailed();
        }

    }

    /**
     * 弹出提示信息
     */
    @Override
    public void showMessage(String msg) {

    }

    /**
     * 显示空View
     */
    @Override
    public void showEmptyView() {
        if (null == holder) {
            initGloadingView();
        }
        if (holder != null) {
            holder.showEmpty();
        }

    }

    /**
     * 重新加载 --子类里面重写
     */
    @Override
    public void onLoadRetry() {

    }

    /**
     * 现在加载中提示框 DIALOG类型
     */
    @Override
    public void showLoadingDialog() {
        if (null == holder) {
            initGloadingView();
        }
        if (holder != null) {
            holder.showLoading();
        }
        LogUtils.e("显示加载中....");
    }

    /**
     * 隐藏加载中提示框
     */
    @Override
    public void hideLoadingDialog() {
        if (null == holder) {
            initGloadingView();
        }
        if (holder != null) {
            holder.showLoadSuccess();
        }
        LogUtils.e("隐藏了loading");
    }

    @Override
    public LifecycleProvider<Lifecycle.Event> getProvider() {
        return AndroidLifecycle.createLifecycleProvider(this);
    }

    /**
     * 隐藏软键盘
     */
    public void hideSoftKeyBoard() {
        View localView = getCurrentFocus();
        if (this.mInputMethodManager == null) {
            this.mInputMethodManager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
        }
        if ((localView != null) && (this.mInputMethodManager != null)) {
            LogUtils.e("隐藏软键盘呀");
            this.mInputMethodManager.hideSoftInputFromWindow(localView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 用户被踢出 或者是 token过期
     */
    @Override
    public void showKickOutDialog(String msg) {
        TextView msgText = new TextView(this);
        msgText.setText(TextUtils.isEmpty(msg) ? msg : "账号已失效或在其他地方登录，请重新登录");
        msgText.setPadding(10, 30, 10, 10);
        msgText.setGravity(Gravity.CENTER);
        msgText.setTextSize(15);
        kickOutDialog = new AlertDialog.Builder(context)
                .setView(msgText)
                .setPositiveButton("确定", (dialog, which) -> {
                    dialog.dismiss();
                    PersistentCookieStore.getInstance(getApplication()).removeAll();
                    AppManager.getInstance().exitApp();
                    ARouterUtils.navigation("/login/LoginActivity");

                })
                .show();
    }

}
